﻿using DevTeam;


using System;
using System.Data;

namespace ConfExpert.Forms.ImportWizards.Invoice
{
    public partial class Du4 : XImportWizard
    {
        DataTable dtDetail;
        DataTable dtMaster;

        public Du4()
        {
            InitializeComponent();
            Init("Du4 Fatura Dosyası", true);

            this.FileDone += Du4_FileDone;
            this.ProcessDone += Du4_ProcessDone;
            this.ProcessStart += Du4_ProcessStart;
            btnSave.Enabled = false;
            btnSave.ItemClick += BtnSave_ItemClick;
        }

        private void Du4_ProcessStart()
        {
            dtMaster = new DataTable();
            dtMaster.TableName = "Invoice";
            dtMaster.Columns.Add("SheetName", typeof(string));
            dtMaster.Columns.Add("FileName", typeof(string));
            dtMaster.Columns.Add("InvoiceNo", typeof(string));
            dtMaster.Columns.Add("InvoiceDate", typeof(DateTime));
            dtMaster.AddAutoIncrementalColumn("InvoiceID");
            //dtMaster.Columns.Add("InvoiceID", typeof(int));
            //dtMaster.Columns["InvoiceID"].AutoIncrementSeed = 1;
            //dtMaster.Columns["InvoiceID"].AutoIncrement = true;
            dtMaster.PrimaryKey = new DataColumn[] { dtMaster.Columns["InvoiceID"] };

            dtDetail = new DataTable();
            dtDetail.TableName = "InvoiceLines";
            dtDetail.AddAutoIncrementalColumn("InvoiceLinesID");
            //dtDetail.Columns.Add("InvoiceLinesID", typeof(int));
            //dtDetail.Columns["InvoiceLinesID"].AutoIncrementSeed = 1;
            //dtDetail.Columns["InvoiceLinesID"].AutoIncrement = true;
            dtDetail.PrimaryKey = new DataColumn[] { dtDetail.Columns["InvoiceLinesID"] };
            dtDetail.Columns.Add("InvoiceID", typeof(int));
            dtDetail.Columns.Add("idx", typeof(int));
            dtDetail.Columns.Add("Blatt", typeof(string));
            dtDetail.Columns.Add("PA", typeof(string));
            dtDetail.Columns.Add("OrderNo", typeof(string));
            dtDetail.Columns.Add("CusNo", typeof(string));
            dtDetail.Columns.Add("Label", typeof(string));
            dtDetail.Columns.Add("Article", typeof(string));
            dtDetail.Columns.Add("Colour", typeof(string));
            dtDetail.Columns.Add("ModelNo", typeof(string));
            dtDetail.Columns.Add("Model", typeof(string));
            dtDetail.Columns.Add("UnitPrice", typeof(decimal));
            dtDetail.Columns.Add("Qty", typeof(int));


            DataSet dsResult = new DataSet();
            dsResult.Tables.Add(dtMaster);
            dsResult.Tables.Add(dtDetail);
        }

        private void Du4_ProcessDone()
        {
            string xml = dtDetail.Serialize();
            DataTable result = ExecuteDataTable("GetIdxFromInvoice", "Du4Orders", xml);
            foreach (DataRow dr in result.Rows)
            {
                dtDetail.Rows.Find(dr["InvoiceLinesId"])["idx"] = dr["idx"];
            }

            MasterGrid.Init(dtMaster);
            MasterGrid.AddDetailGrid(DetailGrid, "InvoiceID");


            MasterGrid.AddSummary();
            MasterGrid.BestFitColumns();
            btnSave.Enabled = true;
        }

        private void Du4_FileDone(DataSet ds, string FileName)
        {
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                DataTable dt = ds.Tables[i];
                string upperTableName = dt.TableName.ToUpper();
                if (upperTableName == "INV#CARTON" || upperTableName == "INV#STORE")
                {
                    if (dt.Rows[12][1].ToStr() == "Blatt")
                    {
                        DataRow drMaster = dtMaster.NewRow();
                        drMaster["SheetName"] = dt.TableName.Replace("#", " ");
                        drMaster["FileName"] = FileName;    //*
                        string[] invoiceDates = dt.Rows[1][13].ToStr().Split('/');
                        string invoiceNo = dt.Rows[2][13].ToStr();
                        
                        drMaster["InvoiceNo"] = invoiceNo;
                        DateTime invoiceDate = new DateTime(invoiceDates[2].ToInt(-1), invoiceDates[1].ToInt(-1), invoiceDates[0].ToInt(-1));
                        drMaster["InvoiceDate"] = invoiceDate;
                        
                        dtMaster.Rows.Add(drMaster);

                        DataTable dtSheet = ProcessSheet(dt);

                        foreach (DataRow dr in dtSheet.Rows)
                            dr["InvoiceID"] = drMaster["InvoiceID"];

                        dtDetail.Merge(dtSheet);
                    }
                    else
                        throw new ApplicationException("Dosya, şablona uygun değil");
                }
            }
        }

        private DataTable ProcessSheet(DataTable dt)
        {
            DataTable sheetData = dtDetail.Clone();

            for (int i = 13; i < dt.Rows.Count; i++)
            {
                string firstCell = dt.Rows[i][1].ToStr();

                if (firstCell == "")
                    continue;
                else if (firstCell.ToLower().Trim() == "beneficiary")
                    break;
                else
                {
                    DataRow newRow = sheetData.NewRow();

                    newRow["Blatt"] = dt.Rows[i][1].ToStr();
                    newRow["PA"] = dt.Rows[i][2].ToStr();
                    newRow["OrderNo"] = dt.Rows[i][3].ToStr();
                    newRow["CusNo"] = dt.Rows[i][4].ToStr();
                    newRow["Label"] = dt.Rows[i][5].ToStr();
                    newRow["Article"] = dt.Rows[i][6].ToStr();
                    newRow["Colour"] = dt.Rows[i][7].ToStr();
                    newRow["ModelNo"] = dt.Rows[i][8].ToStr();
                    newRow["Model"] = dt.Rows[i][9].ToStr();
                    newRow["Qty"] = dt.Rows[i][10].ToInt(-1);
                    newRow["UnitPrice"] = dt.Rows[i][12].ToStr().Replace(",", ".").ToDecimal(-1);

                    sheetData.Rows.Add(newRow);
                }
            }
            return sheetData;
        }

        private void BtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string xmlMaster = dtMaster.Serialize();
            string xmlDetail = dtDetail.Serialize();
            ExecuteDataTable("InsSatisFaturasi", "Du4Orders", xmlMaster, xmlDetail);
            ShowInfoMessage("Fatura başarı ile aktarıldı.");
        }

       
    }
}
